package com.zhoug.zmui3;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.util.AttributeSet;
import android.view.animation.LinearInterpolator;

import androidx.annotation.Nullable;

import static android.view.animation.Animation.RESTART;

/**
 * @Author 35574
 * @Date 2020/12/8
 * @Description
 */
public class ZMUILevelAnimImageView extends androidx.appcompat.widget.AppCompatImageView {
    private int imageLevel = 0;
    private int maxLevel = 5;
    private int minLevel = 0;
    private ObjectAnimator mAnimator;

    public ZMUILevelAnimImageView(Context context) {
        this(context, null);
    }

    public ZMUILevelAnimImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ZMUILevelAnimImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setImageLevel(int level) {
        if (this.imageLevel != level) {
            this.imageLevel = level;
            super.setImageLevel(level);
        }

    }

    public int getImageLevel() {
        return imageLevel;
    }

    public void nextLevel() {
        setImageLevel(++imageLevel % maxLevel);
    }

    public void setMaxLevel(int maxLevel) {
        this.maxLevel = maxLevel;
    }

    public void setMinLevel(int minLevel) {
        this.minLevel = minLevel;
    }


    public void startAnim() {
        startAnim(RESTART,1000);
    }

    /**
     *
     * @param repeatMode
     * {@link ObjectAnimator#RESTART}
     * {@link ObjectAnimator#REVERSE}
     *@param duration 动画时间
     */
    public void startAnim(int repeatMode,int duration) {
        if(mAnimator==null){
            Drawable drawable = getDrawable();
            if(drawable instanceof LevelListDrawable){
                mAnimator = ObjectAnimator.ofInt(this, "imageLevel", minLevel, maxLevel);
                mAnimator.setRepeatCount(ObjectAnimator.INFINITE);
                mAnimator.setInterpolator(new LinearInterpolator());
                mAnimator.setRepeatMode(repeatMode);
                mAnimator.setDuration(duration);
            }
        }
        if(mAnimator!=null && !mAnimator.isStarted()){
            mAnimator.start();
        }
    }

    public void stopAnim(){
        if (mAnimator!=null){
            mAnimator.cancel();
            mAnimator=null;
        }
    }



}
